package designPattern.creation.singletonpattern;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登记式单例 -- 维护了一组单例类; 对于已登记的直接返回, 对于未登记的先登记后返回;
 * @author 张琪
 * @date 2023/1/29 18:06
 */
public class Singleton3 {
    /**
     * hashmap线程不安全, 应该为 ConcurrentHashMap
     */
    private static final Map<String, Singleton3> map = new ConcurrentHashMap<>();

    static {
        Singleton3 single = new Singleton3();
        map.put(single.getClass().getName(), single);
    }

    protected Singleton3(){}

    public static Singleton3 getInstance(String name) {
        if (name == null) {
            name = Singleton3.class.getName();
            System.out.println("name == null"+"--->name="+name);
        }
        if (map.get(name) == null) {
            try {
                map.put(name, (Singleton3) Class.forName(name).getDeclaredConstructor(Singleton3.class).newInstance((Object) null));
            } catch (ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        return map.get(name);
    }

    public String about() {
        return "Hello, I am RegSingleton.";
    }
    public static void main(String[] args) {
        Singleton3 single3 = Singleton3.getInstance(null);
        System.out.println(single3.about());
    }

}
